package cn.wolfcode.shop.cloud.filter;

import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.feign.MemberFeignApi;
import cn.wolfcode.shop.cloud.util.CookieUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 做cookie刷新，redis的过期时间刷新,浏览器中的过期时间也要刷新
 *
 */
@Component
public class CookieRefreshFilter extends ZuulFilter {
    @Autowired
    private MemberFeignApi memberFeignApi;
    //声明filter的类型
    @Override
    public String filterType() {
        return "post";
    }
//设置优先级返回值越小优先级越高
    @Override
    public int filterOrder() {
        return 0;
    }
//方法返回true进入run方法里来
    @Override
    public boolean shouldFilter() {
        //如果用户在请求的时候没有携带token那么我们是不需要刷新的
        //如果获取到用户发来的token  ,要用到请求对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        String token = CookieUtil.getToken(request,CookieUtil.COOKIE_NAME);
        if(token == null){
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //判断用户是否带着token，token在cookie里面
        //cokie可以从请求对象中获得，如何获得请求对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        HttpServletResponse response = requestContext.getResponse();
        //获取cookie里面的token
        String token = CookieUtil.getToken(request,CookieUtil.COOKIE_NAME);
        //远程调用会员服务延长redis时间
        Result<Boolean> result = memberFeignApi.refreshTime(token);
        //延长cookie的过期时间
        if(result.getCode() == 200 && result.getData()){
            CookieUtil.addCoolie(CookieUtil.COOKIE_NAME,token,1800,response);
        }
        //可能有很多的filter，设置成false不会往后执行
        requestContext.setSendZuulResponse(false);
        return null;
    }
}
